package com.sikao.app.ui;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Looper;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.Toast;

import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshScrollView;
import com.sikao.app.R;
import com.sikao.app.adapter.ProductExtraInfAdapter;
import com.sikao.app.adapter.TenderOrderListAdapter;
import com.sikao.app.bean.AddCollectBean;
import com.sikao.app.bean.AddCollectSubmitBean;
import com.sikao.app.bean.BidListBean;
import com.sikao.app.bean.BidListSubmitBean;
import com.sikao.app.bean.CancelCollectBean;
import com.sikao.app.bean.CancelCollectSubmitBean;
import com.sikao.app.bean.CheckCollectBean;
import com.sikao.app.bean.CheckCollectSubmitBean;
import com.sikao.app.bean.InviteDetailBean;
import com.sikao.app.bean.InviteDetailSubmitBean;
import com.sikao.app.bean.ProductIndexBean;
import com.sikao.app.bean.ProductIndexListBeans;
import com.sikao.app.dao.AddCollectModel;
import com.sikao.app.dao.BidListModel;
import com.sikao.app.dao.CancelCollectModel;
import com.sikao.app.dao.CheckCollectModel;
import com.sikao.app.dao.InviteDetailModel;
import com.sikao.app.net.OnNetBackListener;
import com.sikao.app.ui.base.BaseActivity;
import com.sikao.app.utils.ConstantClass;
import com.sikao.app.utils.JSONUtil;
import com.sikao.app.utils.Utils;
import com.sikao.app.view.CountDownLinearLayout;
import com.sikao.app.view.MyGridView;
import com.sikao.app.view.MyListView;

import java.util.ArrayList;
import java.util.List;

/**
 * 招标详情
 * [39-77]招标详情
 */
public class TenderDetailsActivity extends BaseActivity implements View.OnClickListener {

	private TextView titleTv;
	private ImageView backIv;

	private TextView tvTenderName1;
	private TextView tvViewTimes;
	private TextView tvSupply;
	private TextView tvAmountUnit1;
	private TextView tvTenderPrice;
	private TextView tvOfferTimes;
	private TextView tvPhone;
	private TextView tvPurchasedAmount;
	private TextView tvAmountUnit2;
	private CountDownLinearLayout cdll;//倒计时控件
	private TextView tvType;
	private TextView tvName;
	private TextView tvProductCode;
	private TextView tvIsPorted;
	private TextView tvMinimumSupply;
	private TextView tvGuaranteedProportion;
	private TextView tvGuadanType;
	private TextView tvDeliveryArea;
	private TextView tvBargainingRules;
	//private GridView productIndexGridView;
	private MyListView productIndexListView;
	private MyListView listviewOrderList;//投标记录
	private LinearLayout linearlayout,ll_details_tv1;

	String inviteId = "";
	InviteDetailBean InviteDetailBean;
	//是否收藏
	private boolean isCollected = false;
	//收藏的id
	private String collectId = "0";
	//private ProductIndexAdapter productIndexAdapter;
	private ProductExtraInfAdapter productExtraInfAdapter;
	private TenderOrderListAdapter tenderOrderListAdapter;// 投标记录
	private PullToRefreshScrollView mPullRefreshScrollView;

	//产品指标
	private List<ProductIndexBean> productIndexBeanList = new ArrayList<ProductIndexBean>();
	private List<ProductIndexListBeans> productIndexListBeanses = new ArrayList<>();
	//投标记录
	private List<BidListBean.ResBean.ListBean> tenderOrderList = new ArrayList<BidListBean.ResBean.ListBean>();
	public static TenderDetailsActivity tenderDetailsActivity;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		setContentView(R.layout.activity_tender_details);
		super.onCreate(savedInstanceState);
		tenderDetailsActivity = this;
	}

	@Override
	protected void init() {
		titleTv.setText("招标详情");
		backIv.setVisibility(View.VISIBLE);
		//productIndexAdapter = new ProductIndexAdapter(this, productIndexBeanList);
		//productIndexGridView.setAdapter(productIndexAdapter);
		productExtraInfAdapter = new ProductExtraInfAdapter(this, productIndexListBeanses);
		productIndexListView.setAdapter(productExtraInfAdapter);
		tenderOrderListAdapter = new TenderOrderListAdapter(this, tenderOrderList);
		listviewOrderList.setAdapter(tenderOrderListAdapter);

		//获取招标详情
		getTenderDetails(true);
		//获取投标记录
		getTenderOrderList(false);
		if (ConstantClass.state == 1) {//如果已经登录检查是否收藏
			checkCollect(true);
		}
	}

	private void getTenderOrderList(boolean flag) {
		//tenderOrderList
		BidListSubmitBean bidListSubmitBean = new BidListSubmitBean(inviteId, "1", "1000");
		BidListModel bidListModel = new BidListModel(this, new OnNetBackListener<BidListBean>() {
			@Override
			public void netBack(BidListBean data) {
				if (data == null) {
					Toast.makeText(TenderDetailsActivity.this, data.getMsg(), Toast.LENGTH_SHORT).show();
				} else {
					if (data.getStatus() == 1) {
						tenderOrderList.clear();
						tenderOrderList.addAll(data.getRes().getList());
						tenderOrderListAdapter.notifyDataSetChanged();
					} else {
						//Toast.makeText(TenderDetailsActivity.this, data.getMsg(), Toast.LENGTH_SHORT).show();
					}
				}
			}
		});
		bidListModel.request(JSONUtil.toJSON(bidListSubmitBean), flag);

	}

	@Override
	protected void initData() {
		Intent intent = getIntent();
		inviteId = intent.getStringExtra("inviteId");

	}


	private void getTenderDetails(boolean flag) {
		InviteDetailSubmitBean inviteDetailSubmitBean = new InviteDetailSubmitBean();
		inviteDetailSubmitBean.setInviteId(inviteId);
		InviteDetailModel inviteDetailModel = new InviteDetailModel(this, new OnNetBackListener<InviteDetailBean>() {
			@Override
			public void netBack(InviteDetailBean data) {
				if (data == null) {
					Toast.makeText(TenderDetailsActivity.this, data.getMsg(), Toast.LENGTH_SHORT).show();
				} else {
					if (data.getStatus() == 1) {
						InviteDetailBean = data;
						initViewData();
						//取消刷新状态
						mPullRefreshScrollView.onRefreshComplete();
					} else {
						Toast.makeText(TenderDetailsActivity.this, data.getMsg(), Toast.LENGTH_SHORT).show();
					}
				}
			}
		});
		inviteDetailModel.request(JSONUtil.toJSON(inviteDetailSubmitBean), flag);
	}

	private void initViewData() {
		tvTenderName1.setText(InviteDetailBean.getRes().getTitle());
		tvViewTimes.setText("浏览人气：" + InviteDetailBean.getRes().getView_times());
		tvSupply.setText(InviteDetailBean.getRes().getOrigin_number());//原始的需求量
		tvAmountUnit1.setText(InviteDetailBean.getRes().getUnit());
		tvTenderPrice.setText(InviteDetailBean.getRes().getPrice());
		tvOfferTimes.setText(InviteDetailBean.getRes().getStatus_str());//投标人数
		tvPhone.setText(InviteDetailBean.getRes().getPhone() + "");//联系电话
		tvPurchasedAmount.setText(InviteDetailBean.getRes().getHad_number() + "");//已经采购数量
		tvAmountUnit2.setText(InviteDetailBean.getRes().getUnit());


		tvType.setText(InviteDetailBean.getRes().getCat_name());
		tvName.setText(InviteDetailBean.getRes().getName() + "");
		tvProductCode.setText(InviteDetailBean.getRes().getProduct_code());
		tvIsPorted.setText(InviteDetailBean.getRes().getIs_ported_str());
		tvMinimumSupply.setText(InviteDetailBean.getRes().getLeast_number());
		tvGuaranteedProportion.setText(InviteDetailBean.getRes().getMargin_scale() + "%");
		tvGuadanType.setText(InviteDetailBean.getRes().getPublish_type_str());
		tvDeliveryArea.setText(InviteDetailBean.getRes().getDelivery_area());
		tvBargainingRules.setText(InviteDetailBean.getRes().getPay_role() + "");

		MyGridView gridViewAttrs;
		MyListView listviewOrderList;

		long endTime = Long.parseLong(TextUtils.isEmpty(InviteDetailBean.getRes().getEnd_time()) ? "0" : InviteDetailBean.getRes().getEnd_time());
	//	Utils.showToast("结束时间" + endTime);
		cdll.startCountDown(endTime);


		//处理数据 将数据处理的和商品属性里的数据格式一样

	/*
	 [0] => Array
                        (
                            [attrId] => 7
                            [changePrice] => 0
                            [value] => 多选测试1
                            [name] => 多选测试
                            [attrType] => 4
                        )

                    [1] => Array
                        (
                            [attrId] => 7
                            [changePrice] => 0
                            [value] => 多选测试3
                            [name] => 多选测试
                            [attrType] => 4
                        )


	[0] => Array
				(
				[id] => 3
				[name] => 煤燃烧值
				[attr_type] => 3
				[attr_values] => 10000大卡,7000大卡,5000大卡,3000大卡,1000大卡
				[default_value] => Array
				(
				[0] => 10000大卡
				[1] => 7000大卡
				[2] => 5000大卡
		)
*/


		//产品指标
		List<InviteDetailBean.ResBean.GoodsAttrsBean> getGoods_attrs = InviteDetailBean.getRes().getGoods_attrs();
		productIndexBeanList.clear();
		productIndexListBeanses.clear();
		if (getGoods_attrs != null && getGoods_attrs.size() > 0) {
			for (int i = 0; i < getGoods_attrs.size(); i++) {//构造符合条件的数据

				ProductIndexBean productIndexBean = new ProductIndexBean();
				List<String> values = new ArrayList<>();
				values.add(getGoods_attrs.get(i).getValue());

				productIndexBean.setId(getGoods_attrs.get(i).getAttrId());
				productIndexBean.setName(getGoods_attrs.get(i).getName());
				productIndexBean.setDefault_value(values);
				productIndexBeanList.add(productIndexBean);

				for (int j = 0; j < productIndexBeanList.size(); j++) {
					if (productIndexBeanList.get(j)==null||getGoods_attrs.get(i)==null||"".equals(productIndexBeanList.get(j))||"".equals(getGoods_attrs.get(i))){
						break;
					}
					if (productIndexBeanList.get(j).getId().equals(getGoods_attrs.get(i).getAttrId())
							&& !(productIndexBeanList.get(j).getDefault_value_toString().equals(getGoods_attrs.get(i).getValue()))) {
						//如果是相同的类型 则合并数据
						productIndexBeanList.get(j).getDefault_value().add(getGoods_attrs.get(i).getValue());
						//从数据集合中移除此项
						productIndexBeanList.remove(productIndexBean);

					}
				}
			}
			ProductIndexListBeans productIndexListBeans = null;
			for (int i = 0; i < productIndexBeanList.size(); i++) {//构造符合条件的数据
				if (i == 0 || i % 2 == 0) {
					productIndexListBeans = new ProductIndexListBeans();
					productIndexListBeanses.add(productIndexListBeans);
				}
				productIndexListBeans.getBeans().add((productIndexBeanList.get(i)));
			}
		}


      /*  if (getGoods_attrs != null && getGoods_attrs.size() > 0) {//需要修改

			for (int i = 0; i < getGoods_attrs.size(); i++) {
				if (!("3".equals(getGoods_attrs.get(i).getAttrType())) && !("5".equals(getGoods_attrs.get(i).getAttrType()))) {
					ProductIndexBean productIndexBean = new ProductIndexBean();
					productIndexBean.setId(getGoods_attrs.get(i).getId());
					productIndexBean.setName(getGoods_attrs.get(i).getName());
					productIndexBean.setDefault_value(getGoods_attrs.get(i).getDefault_value());

					productIndexBeanList.add(productIndexBean);

				}

			}
        }*/


		productExtraInfAdapter.notifyDataSetChanged();


	}

	@Override
	protected void initView() {

		titleTv = (TextView) findViewById(R.id.title_middle_tv);
		backIv = (ImageView) findViewById(R.id.title_left_img);
		tvTenderName1 = (TextView) findViewById(R.id.tv_tender_name1);
		tvViewTimes = (TextView) findViewById(R.id.tv_view_times);
		tvSupply = (TextView) findViewById(R.id.tv_supply);
		tvAmountUnit1 = (TextView) findViewById(R.id.tv_amount_unit1);
		tvTenderPrice = (TextView) findViewById(R.id.tv_tender_price);
		tvOfferTimes = (TextView) findViewById(R.id.tv_offer_times);
		tvPhone = (TextView) findViewById(R.id.tv_phone);
		tvPurchasedAmount = (TextView) findViewById(R.id.tv_purchased_amount);
		tvAmountUnit2 = (TextView) findViewById(R.id.tv_amount_unit2);
		cdll = (CountDownLinearLayout) findViewById(R.id.cdll);
		tvType = (TextView) findViewById(R.id.tv_type);
		tvName = (TextView) findViewById(R.id.tv_name);
		tvProductCode = (TextView) findViewById(R.id.tv_product_code);
		tvIsPorted = (TextView) findViewById(R.id.tv_is_ported);
		tvMinimumSupply = (TextView) findViewById(R.id.tv_minimum_supply);
		tvGuaranteedProportion = (TextView) findViewById(R.id.tv_guaranteed_proportion);
		tvGuadanType = (TextView) findViewById(R.id.tv_guadan_type);
		tvDeliveryArea = (TextView) findViewById(R.id.tv_delivery_area);
		tvBargainingRules = (TextView) findViewById(R.id.tv_bargaining_rules);
		//productIndexGridView = (GridView) findViewById(R.id.gridView_attrs);
		productIndexListView = (MyListView) findViewById(R.id.listview_attrs);
		listviewOrderList = (MyListView) findViewById(R.id.listview_order_list);
		linearlayout = (LinearLayout) findViewById(R.id.linearlayout);
		ll_details_tv1 = (LinearLayout) findViewById(R.id.ll_details_tv1);
		ll_details_tv1.setOnClickListener(this);
		findViewById(R.id.btn_collect).setOnClickListener(this);
		findViewById(R.id.btn_order).setOnClickListener(this);

		mPullRefreshScrollView = (PullToRefreshScrollView) findViewById(R.id.pull_refresh_scrollview);
		mPullRefreshScrollView.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener<ScrollView>() {

			@Override
			public void onRefresh(PullToRefreshBase<ScrollView> refreshView) {
				onRefreshGetData();
			}

		});

	}

	private void onRefreshGetData() {

		//获取招标详情
		getTenderDetails(false);
		//获取投标记录
		getTenderOrderList(false);
		if (ConstantClass.state == 1) {//如果已经登录检查是否收藏
			checkCollect(false);
		}
	}

	@Override
	protected void initListener() {
		backIv.setOnClickListener(this);
	}


	@Override
	public void onClick(View v) {
		switch (v.getId()) {
			case R.id.title_left_img:
				finish();
				break;
			case R.id.btn_order:
				Intent intent = new Intent();
				if (ConstantClass.state == 0) {
					intent.setClass(this, LoginActivity.class);
				} else if (!ConstantClass.isSeller) {
					intent.setClass(this, CompanyApplyActivity.class);
				} else {
					intent.setClass(TenderDetailsActivity.this, TenderOrderActivity.class);
					intent.putExtra("inviteId", inviteId);
					intent.putExtra("number", InviteDetailBean.getRes().getNumber());
					intent.putExtra("leastNumber", InviteDetailBean.getRes().getLeast_number());
					intent.putExtra("unit", InviteDetailBean.getRes().getUnit());
				}
				startActivity(intent);

				break;
			case R.id.btn_collect:
				if (ConstantClass.state == 0) {
					Intent intent2 = new Intent();
					intent2.setClass(this, LoginActivity.class);
					startActivity(intent2);
					return;
				} else {
					if (isCollected) {//已经收藏 取消收藏
						removeCollect();
					} else {//未收藏 去收藏
						addCollect("invite", InviteDetailBean.getRes().getId());
					}
				}
				break;
			case R.id.ll_details_tv1://联系电话
  					if (!TextUtils.isEmpty(tvPhone.getText())){
						AlertDialog dialog;
						AlertDialog.Builder builder = new AlertDialog.Builder(this);
						builder.setTitle("确认拨打电话吗?");
						builder.setMessage(tvPhone.getText());
						builder.setPositiveButton("确认", new DialogInterface.OnClickListener() {
							@Override
							public void onClick(DialogInterface dialog, int which) {
								dialog.dismiss();
								Intent intent = new Intent(Intent.ACTION_DIAL);
								Uri data = Uri.parse("tel:" + tvPhone.getText());
								intent.setData(data);
								startActivity(intent);

							}
						});
						builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
							@Override
							public void onClick(DialogInterface dialog, int which) {
								dialog.dismiss();
							}
						});
						dialog = builder.create();
						dialog.show();
					}


				break;
			default:
				break;
		}
	}

	private void removeCollect() {//取消收藏
		CancelCollectSubmitBean cancelCollectSubmitBean = new CancelCollectSubmitBean();
		cancelCollectSubmitBean.setId(collectId);

		new CancelCollectModel(this, new OnNetBackListener<CancelCollectBean>() {
			@Override
			public void netBack(CancelCollectBean data) {
				if (data == null) {
					Toast.makeText(TenderDetailsActivity.this, data.getMsg(), Toast.LENGTH_SHORT).show();
				} else {
					if (data.getStatus() == 1) {//成功取消
						isCollected = false;
						((Button) findViewById(R.id.btn_collect)).setText("收藏");
					} else {
						Toast.makeText(TenderDetailsActivity.this, data.getMsg(), Toast.LENGTH_SHORT).show();
					}
				}
			}
		}).request(JSONUtil.toJSON(cancelCollectSubmitBean), true);
	}

	private void addCollect(String type, String objId) {
		new AddCollectModel(this, new OnNetBackListener<AddCollectBean>() {
			@Override
			public void netBack(AddCollectBean data) {
				if (data == null) {
					Toast.makeText(TenderDetailsActivity.this, data.getMsg(), Toast.LENGTH_SHORT).show();
				} else {
					if (data.getStatus() == 1) {
						//Toast.makeText(MallDetailsActivity.this, data.getMsg(), Toast.LENGTH_SHORT).show();
						checkCollect(true);
					} else {
						Toast.makeText(TenderDetailsActivity.this, data.getMsg(), Toast.LENGTH_SHORT).show();
					}
				}
			}
		}).request(JSONUtil.toJSON(new AddCollectSubmitBean(type, objId)), true);

	}

	private void checkCollect(boolean flag) {
		CheckCollectSubmitBean checkCollectSubmitBean = new CheckCollectSubmitBean();
		checkCollectSubmitBean.setObjId(inviteId);
		checkCollectSubmitBean.setType("invite");

		new CheckCollectModel(this, new OnNetBackListener<CheckCollectBean>() {
			@Override
			public void netBack(CheckCollectBean data) {
				if (data == null) {
					Toast.makeText(TenderDetailsActivity.this, data.getMsg(), Toast.LENGTH_SHORT).show();
				} else {
					if (data.getStatus() == 1) {
						if ("1".equals(data.getRes().getStatus())) {//已经收藏
							isCollected = true;
							((Button) findViewById(R.id.btn_collect)).setText("已收藏");
							collectId = data.getRes().getId();
						} else {
							isCollected = false;
							((Button) findViewById(R.id.btn_collect)).setText("收藏");
						}
					} else {
						Toast.makeText(TenderDetailsActivity.this, data.getMsg(), Toast.LENGTH_SHORT).show();
					}
				}
			}
		}).request(JSONUtil.toJSON(checkCollectSubmitBean), flag);
	}

	@Override
	protected void onResume() {
		super.onResume();
		if (ConstantClass.state == 1) {//如果已经登录检查是否收藏
			checkCollect(true);
		}
	}

	@Override
	protected void onDestroy() {
		cdll.stopTimer();
		super.onDestroy();
	}
}
